package com.study.rpc10.client;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.study.rpc10.common.HessianUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * 10中将ObjectInputStream和ObjectOutputStream
 * 替换为Hessian2Input和Hessian2Output
 */
public class Stub {

    public static Object getStub(Class clazz) {
        InvocationHandler h = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket s = new Socket("127.0.0.1", 8888);

                Hessian2Output oos = new Hessian2Output(s.getOutputStream());

                String clazzName = clazz.getName();
                String methodName = method.getName();
                Class<?>[] parameterTypes = method.getParameterTypes();

                oos.writeString(clazzName);
                oos.writeString(methodName);
                oos.writeObject(parameterTypes);
                oos.writeObject(args);
                oos.flush();

                //序列化传输
                Hessian2Input ois = new Hessian2Input(s.getInputStream());
                Object o = HessianUtil.deserialize(ois.readBytes());

                oos.close();
                s.close();
                return o;
            }
        };
        //生成IUserService的动态代理类，对接口中的每个方法调用时执行代理方法
        Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, h);
        return o;
    }
}
